package com.example.psychologicalappointmentsystem.config.auth;

import com.example.psychologicalappointmentsystem.Entity.User;
import com.example.psychologicalappointmentsystem.Enum.UserRole;
import com.example.psychologicalappointmentsystem.JpaRepository.UserRepository;
import com.example.psychologicalappointmentsystem.common.ParamCheck;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class ThreadLocalInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserRepository userDao;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求用户取用户token
        String Token = request.getHeader("Authorization");
        String userToken = Token.substring(7); // 去掉 "Bearer " 前缀
        try {
            if (StringUtils.isNotBlank(userToken)) {
                // 查询用户信息，获取用户id
                User userInfoObject = userDao.findByToken(userToken);
                Long userId = userInfoObject.getId();
                ParamCheck.mustNonNull(userInfoObject, "用户不存在或已被停用");
                UserRole type = userInfoObject.getRole();
                // 保存到threadLocal
                MyThreadLocalModel myThreadLocalModel = new MyThreadLocalModel();
                myThreadLocalModel.setUserId(userId);
                myThreadLocalModel.setToken(userToken);
                myThreadLocalModel.setUserRole(type);
                PsyThreadLocalUtil.set(myThreadLocalModel);
                // 正常业务
                return super.preHandle(request, response, handler);
            }
            //没有权限，返回
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            String ErrorBody = "用户token为空，或者用户没权限，请检查头部信息：Authorization";
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(ErrorBody);
            return false;
        } catch (Exception e) {
            log.error("权限拦截器异常" + e.getMessage(), e);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            String ErrorBody = "用户token为空，或者用户没权限，请检查头部信息：Authorization";
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(ErrorBody);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 离开时删除当前threadlocal的值
        PsyThreadLocalUtil.clear();
        super.postHandle(request, response, handler, modelAndView);
    }

}
